<template>
    <div v-loading="isUploading">
      <quill-editor v-model="content" :options="editorOption" class="qe" ref="editor" :style="editorStyle"></quill-editor>

      <form method="post" enctype="multipart/form-data" style="display:none">
        <input :id="uuid" name="file" type="file" multiple ref="imageFile" @change="selectFile" accept="image/*">
      </form>
    </div>
</template>
<script>
import Quill from "quill";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import md5 from "js-md5";
import axios from "axios";
import Api from "api/api";
const axiosInstance = axios.create({});

export default {
  props: {
    value: [String, Array],
    placeholder: String,
    height: String,
    uploadSuffix: String
  },
  created() {
    this.uuid = Math.random()
      .toString(36)
      .substring(3, 8);
    this.content = this.value;
  },
  mounted() {
    this.$refs.editor.quill
      .getModule("toolbar")
      .addHandler("image", this.imageHandler);
  },
  data() {
    return {
      localUpload: false,
      content: "",
      editorOption: {
        placeholder: this.placeholder,
        modules: {
          toolbar: [
            [{ list: "ordered" }, { list: "bullet" }],
            ["image"],
            [{ header: [1, 2, 3, false] }],
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ script: "sub" }, { script: "super" }],
            [{ indent: "-1" }, { indent: "+1" }],
            [{ direction: "rtl" }],
            [{ size: ["small", false, "large", "huge"] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ font: [] }],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            ["clean"]
          ],
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          }
        }
      },
      isUploading: false
    };
  },
  computed: {
    editorStyle() {
      return { height: this.height };
    }
  },
  watch: {
    content(val) {
      this.$emit("input", val);
    },
    value(val) {
      this.content = val;
    }
  },
  methods: {
    // 点击图片按钮
    imageHandler(image) {
      this.$refs.imageFile.click();
    },
    // 选择上传文件
    selectFile: async function(e) {
      // var vm = this
      const file = e.target.files[0];
      const isAcceptType = new RegExp("image/*", "i").test(file.type);

      if (!isAcceptType) {
        this.$notify({
          title: "请选择图片类型文件",
          type: "danger"
        });
        return false;
      }
      if (e.target.files.length) {
        for (let i = 0; i < e.target.files.length; i++) {
          let currentFile = e.target.files[i];
          // 计算文件key
          let tmp = `${currentFile.lastModified +
            currentFile.size +
            Date.now()}`;
          let nameArr = currentFile.name.split(".");
          let extName = nameArr[nameArr.length - 1];
          let key = md5(tmp).substr(0, 10) + "_" + "." + extName;
          this.isUploading = true;
          let token = "";
          if (this.localUpload) {
            token = window.sessionStorage.getItem("token");
          } else {
            token = await this.getToken(key);
          }
          let imgUrl = await this.uploadQN(currentFile, token, this.key);
          console.log(imgUrl);
          if (imgUrl !== null) this.insertImage(imgUrl);
          this.isUploading = false;
        }
      }
    },
    // 上传到七牛
    uploadQN(file, token, key) {
      var fd = new FormData();
      fd.append("token", token);
      fd.append("key", key);
      fd.append("file", file);

      return axiosInstance({
        method: "POST",
        url: this.$appConf.domain.uploadUrl,
        data: fd,
        onUploadProgress: function(progressEvent) {
          var percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(percentCompleted);
        }
      })
        .then(res => {
          // if (res.data.errorMsg !== "success") {
          //   this.$notify({
          //     title: res.data.errorMsg,
          //     type: "danger"
          //   });
          //   return null;
          // } else {
          var imgUrl = `${window.api.imageDomain}${res.data.key}`;
          console.log("imgUrl", imgUrl);
          return imgUrl;
          // }
        })
        .catch(function(err) {
          console.log("err", err);
        });
    },
    // 获取七牛上传token
    getToken(key) {
      return Api.getUploadFileToken({ fileName: key }).then(ret => {
        this.key = ret.data.data.key;
        return ret.data.data.token;
      });
    },
    insertImage(value) {
      // 获取光标位置对象，里面有两个属性，一个是index 还有 一个length，这里要用range.index，即当前光标之前的内容长度，然后再利用 insertEmbed(length, 'image', imageUrl)，插入图片即可。
      let addRange = this.$refs.editor.quill.getSelection();
      value = value.indexOf("http") !== -1 ? value : "http:" + value;
      this.$refs.editor.quill.insertEmbed(
        addRange !== null ? addRange.index : 0,
        "image",
        value,
        Quill.sources.USER
      ); // 调用编辑器的 insertEmbed 方法，插入URL
    }
  },
  components: {
    quillEditor
  }
};
</script>
<style>
.qe {
  line-height: 0;
  margin-bottom: 42px;
}
.ql-snow .ql-picker-options .ql-picker-item {
  line-height: 22px;
}
</style>
